package com.jacklin.service.Impl;

import com.jacklin.DTO.OrderDTO;
import com.jacklin.enums.ResultEnum;
import com.jacklin.exception.MyException;
import com.jacklin.service.BuyerService;
import com.jacklin.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Author:JackLin
 * @Create 2019/4/1 10:40
 */

@Slf4j
@Service
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderService orderService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {

        return checkOrderOwner(openid, orderId);

    }

    @Override
    public OrderDTO cancelOrder(String openid, String orderId) {
        OrderDTO orderDTO = checkOrderOwner(openid, orderId);
        if (orderDTO==null){
            log.error("【取消订单】查不到该订单,orderId={},openid={}", orderId,openid);
            throw new MyException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderService.cancel(orderDTO);
    }

    /**
     * 查询订单和取消订单都要判断订单是否为空，这个抽出来定义一个新的方法checkOrderOwner
     * @param openid
     * @param orderId
     * @return
     */
    private OrderDTO checkOrderOwner(String openid, String orderId){
        OrderDTO orderDTO = orderService.findOne(orderId);
        //先判断订单是否为空
        if (orderDTO==null){
            return null;
        }
        //判断是否是自己的订单
        if (!orderDTO.getBuyerOpenid().equalsIgnoreCase(openid)){//equalsIgnoreCase忽略大小写
            log.error("【查询订单】订单openid不一致. openid={},orderDTO={}",openid,orderDTO );
            throw new MyException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return orderDTO;
    }
}
